﻿' **  Project Home: http://code.google.com/p/yahoo-finance-managed/
' **  
' ******************************************************************************
' **  
' **  Copyright 2011 Marius Häusler
' **  
' **  Licensed under the Apache License, Version 2.0 (the "License");
' **  you may not use this file except in compliance with the License.
' **  You may obtain a copy of the License at
' **  
' **    http://www.apache.org/licenses/LICENSE-2.0
' **  
' **  Unless required by applicable law or agreed to in writing, software
' **  distributed under the License is distributed on an "AS IS" BASIS,
' **  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' **  See the License for the specific language governing permissions and
' **  limitations under the License.
' ** 
' ******************************************************************************


Namespace YahooManaged.Finance.Indicators

    ''' <summary>
    ''' Exponential Moving Average Indicator. Inherits from Moving Average(MA).
    ''' </summary>
    ''' <remarks></remarks>
    Public Class EMA
        Inherits MA

        Public Overrides ReadOnly Property Name() As String
            Get
                Return "Exponential Moving Average"
            End Get
        End Property

        ''' <summary>
        ''' Calculates values of Exponential Moving Average for historic quote values.
        ''' </summary>
        ''' <param name="values">An unsorted IEnumerable of HistQuoteData.</param>
        ''' <returns>The sorted dictionaries. 1) EMA values; 2) MA values; 3) Quote values.</returns>
        ''' <remarks></remarks>
        Public Overrides Function Calculate(ByVal values As IEnumerable(Of KeyValuePair(Of Date, Double))) As Dictionary(Of Date, Double)()
            Dim emaResult As New Dictionary(Of Date, Double)
            Dim baseResults = MyBase.Calculate(values)
            Dim maResult As Dictionary(Of Date, Double) = baseResults(0)

            Dim histQuoteCloses As New List(Of KeyValuePair(Of Date, Double))(baseResults(1))

            Dim exponent As Double = 0
            Dim d As Date
            If histQuoteCloses.Count > 1 Then
                emaResult.Add(histQuoteCloses(0).Key, histQuoteCloses(0).Value)
                For i As Integer = 1 To histQuoteCloses.Count - 1
                    exponent = 2 / (Math.Min(Me.Period, i + 1) + 1)
                    d = histQuoteCloses(i).Key
                    emaResult.Add(d, (exponent * histQuoteCloses(i).Value) + ((1 - exponent) * emaResult(histQuoteCloses(i - 1).Key)))
                Next
            End If

            Return New Dictionary(Of Date, Double)() {emaResult, maResult, baseResults(1)}
        End Function

        Public Overrides Function ToString() As String
            Return Me.Name & " " & Me.Period
        End Function
    End Class

End Namespace